package com.hard;

import android.widget.Toast;

import com.lzscale.scalelib.misclib.Misc;
import com.skyworth.splicing.SerialPortUtil;

import java.nio.ByteBuffer;
import java.util.regex.Pattern;

public class CardReadHelp {

    private static boolean _isLocked = false;
    private ReturnValueCallback returnValueCallback;
    private int timeout;
    private SerialPortUtil mSerialPortUtil;
    private Misc mMisc = Misc.newInstance();


    private volatile static CardReadHelp singleton;
    private CardReadHelp(){
        this.timeout = 20 * 1000;
    }
    public static CardReadHelp getSingleton() {
        if (singleton == null) {
            synchronized (CardReadHelp.class) {
                if (singleton == null) {
                    singleton = new CardReadHelp();
                }
            }
        }
        return singleton;
    }

//    public CardReadHelp() {
//        this.timeout = 20 * 1000;
//    }

    private String cardtype;


    // 激活卡
    public void readCardNum(ReturnValueCallback callback) {

        cardtype = "readCardNum";

        this.setCardNumData(callback, new ReturnValueCallback() {
            @Override
            public void run(ReturnValue rv) {


                if (rv.getIsSuccess()) {

                    String remark = "读卡";


                    readData(remark, new ReadDataListener() {

                        @Override
                        public void readDataCallback(ReturnValue result) {

                            if (result.getIsSuccess()) {//读取成功

                                mMisc.beepEx(100, 50, 3);

                                Object tag = result.getTag();//卡号

                                String userCardNum = (String) tag;

                                ReturnValue rv = new ReturnValue(true, String.valueOf(1), userCardNum);

                                callReturnValueCallback(rv);

                            } else {
                                mMisc.beepWarn();
                                callReturnValueCallback(result);
                            }
                        }
                    });
                } else {
                    callReturnValueCallback(rv);
                }

            }
        });

    }

    //写入卡片内部数据块数据
    public void writeCardBlock(ReturnValueCallback callback, byte[] writeData) {

        cardtype = "writeCardBlock";

        this.setWriteCardBlackData(callback, new ReturnValueCallback() {
            @Override
            public void run(ReturnValue rv) {

                if (rv.getIsSuccess()) {

                    String remark = "数据块数据";

                    readData(remark, new ReadDataListener() {

                        @Override
                        public void readDataCallback(ReturnValue result) {

                            if (result.getIsSuccess()) {//读取成功

                                mMisc.beepEx(100, 50, 3);

                                Object tag = result.getTag();//卡号

                                String userCardNum = (String) tag;

                                ReturnValue rv = new ReturnValue(true, String.valueOf(1), userCardNum);

                                callReturnValueCallback(rv);

                            } else {
                                mMisc.beepWarn();
                                callReturnValueCallback(result);
                            }
                        }
                    });
                } else {
                    callReturnValueCallback(rv);
                }

            }
        }, writeData);

    }
    public void writeCardProductBlock(ReturnValueCallback callback, byte[] writeData) {

        cardtype = "writeCardProductBlock";

        this.setWriteCardProductBlackData(callback, new ReturnValueCallback() {
            @Override
            public void run(ReturnValue rv) {

                if (rv.getIsSuccess()) {

                    String remark = "数据块数据";

                    readData(remark, new ReadDataListener() {

                        @Override
                        public void readDataCallback(ReturnValue result) {

                            if (result.getIsSuccess()) {//读取成功

                                mMisc.beepEx(100, 50, 3);

                                Object tag = result.getTag();//卡号

                                String userCardNum = (String) tag;

                                ReturnValue rv = new ReturnValue(true, String.valueOf(1), userCardNum);

                                callReturnValueCallback(rv);

                            } else {
                                mMisc.beepWarn();
                                callReturnValueCallback(result);
                            }
                        }
                    });
                } else {
                    callReturnValueCallback(rv);
                }

            }
        }, writeData);

    }

    // 读卡
    public void readCardId(ReturnValueCallback callback) {

        cardtype = "readCardId";

        this.setAutoReadBlockData(callback, new ReturnValueCallback() {

            @Override
            public void run(ReturnValue rv) {

                if (rv.getIsSuccess()) {

                    String remark = "读卡";

                    readData(remark, new ReadDataListener() {

                        @Override
                        public void readDataCallback(ReturnValue result) {

                            if (result.getIsSuccess()) {//读取成功

//                                mMisc.beepEx(100, 50, 1);

                                Object tag = result.getTag();//卡号

                                String userCardNum = (String) tag;

                                ReturnValue rv = new ReturnValue(true, String.valueOf(1), userCardNum);

                                callReturnValueCallback(rv);

                            } else {
//                                mMisc.beepWarn();
                                callReturnValueCallback(result);
                            }
                        }
                    });
                } else {
                    callReturnValueCallback(rv);
                }
            }
        });
    }

    // 读卡
    public void readCardIdAndProduct(ReturnValueCallback callback) {

        cardtype = "readCardIdAndProduct";

        this.setAutoReadBlockProductData(callback, new ReturnValueCallback() {

            @Override
            public void run(ReturnValue rv) {

                if (rv.getIsSuccess()) {

                    String remark = "读取产品和员工";

                    readData(remark, new ReadDataListener() {

                        @Override
                        public void readDataCallback(ReturnValue result) {

                            if (result.getIsSuccess()) {//读取成功

//                                mMisc.beepEx(100, 50, 1);

                                Object tag = result.getTag();//卡号

                                String userCardNum = (String) tag;

                                ReturnValue rv = new ReturnValue(true, String.valueOf(1), userCardNum);

                                callReturnValueCallback(rv);

                            } else {
//                                mMisc.beepWarn();
                                callReturnValueCallback(result);
                            }
                        }
                    });
                } else {
                    callReturnValueCallback(rv);
                }
            }
        });
    }

    public void cancelReadCard(ReturnValueCallback callback) {
        if (this.mSerialPortUtil == null) {
            if (callback != null)
                callback.run(new ReturnValue(false, "-1", "没有发起读卡请求，不需要取消"));
            return;
        }
        this.returnValueCallback = callback;
        this.callReturnValueCallback(new ReturnValue(false, "-1", "已取消读卡"));
    }

    private void callReturnValueCallback(ReturnValue result) {
        _isLocked = false;
        if (returnValueCallback != null) {
            returnValueCallback.run(result);
        }
    }

    // 初始化串口, 如果已经打开则先关闭
    private String initSerialPortUtil() {
        try {
            this.closeSerialPort();
            this.mSerialPortUtil = new SerialPortUtil("/dev/ttymxc2", 9600);
            return null;
        } catch (Exception e) {
            return "初始化串口失败:" + e.getMessage();
        }
    }

    private void setWriteCardBlackData(ReturnValueCallback finalCallback, final ReturnValueCallback callback, final byte[] writeData) {
        hand(finalCallback, new Runnable() {

            @Override
            public void run() {

                final String remark = "写入卡号内部数据块数据";

                if (!sendData(getWriteBlock(writeData), remark))
                    return;

//                if (!sendData(getWriteSecretKey(), remark))
//                    return;


                readData(remark, new ReadDataListener() {

                    @Override
                    public void readDataCallback(ReturnValue result) {
                        callback.run(result);
                    }
                });

            }
        });
    }
    private void setWriteCardProductBlackData(ReturnValueCallback finalCallback, final ReturnValueCallback callback, final byte[] writeData) {
        hand(finalCallback, new Runnable() {

            @Override
            public void run() {

                final String remark = "写入卡号内部数据块数据";

                if (!sendData(getWriteProductBlock(writeData), remark))
                    return;

                readData(remark, new ReadDataListener() {

                    @Override
                    public void readDataCallback(ReturnValue result) {
                        callback.run(result);
                    }
                });

            }
        });
    }


    private void setCardNumData(ReturnValueCallback finalCallback, final ReturnValueCallback callback) {
        hand(finalCallback, new Runnable() {

            @Override
            public void run() {

                final String remark = "自动读取人员和产品";

                if (!sendData(getAutoReadCardId(), remark))
                    return;

                readData(remark, new ReadDataListener() {

                    @Override
                    public void readDataCallback(ReturnValue result) {
                        callback.run(result);
                    }
                });

            }
        });
    }
    private void setAutoReadBlockProductData(ReturnValueCallback finalCallback, final ReturnValueCallback callback) {

        hand(finalCallback, new Runnable() {

            @Override
            public void run() {

                final String remark = "自动读取人员和产品";

                if (!sendData(getSetAutoReadBlockProductData(), remark))
                    return;

                readData(remark, new ReadDataListener() {

                    @Override
                    public void readDataCallback(ReturnValue result) {
                        callback.run(result);
                    }
                });

            }
        });
    }

    private void setAutoReadBlockData(ReturnValueCallback finalCallback, final ReturnValueCallback callback) {

        hand(finalCallback, new Runnable() {

            @Override
            public void run() {

                final String remark = "自动读取人员和产品";

                if (!sendData(getSetAutoReadBlockData(), remark))
                    return;

                readData(remark, new ReadDataListener() {

                    @Override
                    public void readDataCallback(ReturnValue result) {
                        callback.run(result);
                    }
                });

            }
        });
    }

    private void hand(ReturnValueCallback callback, final Runnable run) {
        if (!this.isCanLaunchRequest(callback))
            return;
        run.run();
    }

    private boolean sendData(byte[] data, String explain) {
        return this.sendData(data, explain, true);
    }

    // 发送数据
    private boolean sendData(byte[] data, String explain, boolean autoCallReturn) {
        if (this.mSerialPortUtil.sendBuffer(data))
            return true;
        if (autoCallReturn) {
            ReturnValue rv = new ReturnValue(false, "-2", "发送" + explain + "数据失败");
            this.callReturnValueCallback(rv);
        }
        return false;
    }

    private void readData(String explain, ReadDataListener listener) {
        this.readData(this.timeout, explain, listener);
    }

    private void readData(int tTimeout, final String explain, final ReadDataListener listener) {

        this.mSerialPortUtil.readBuffer(tTimeout, new SerialPortUtil.OnDataReceiveListener() {

            @Override
            public void onDataReceive(SerialPortUtil.DataReceType type, byte[] buffer, int size) {

                ReturnValue result;
                String faildStr = "";
                boolean flag = false;
                if (SerialPortUtil.DataReceType.timeout == type) {
                    faildStr = "超时";
                } else if (SerialPortUtil.DataReceType.success != type) {
                    faildStr = "失败";
                } else {
                    flag = true;
                }
                if (!flag) {
                    //105 原 等于 -2
                    result = new ReturnValue(false, "105", "读取" + explain + "响应数据" + faildStr);
                    listener.readDataCallback(result);
                    return;
                }

                String hex = getHexStr(buffer, size);

                // data == null size = 6

                String strRes = "";

                if (cardtype.equals("writeCardBlock")) {

                    if (size == 6 && buffer[0] == 0x20 && buffer[size - 1] == 0x03 && buffer[2] == 0x00 && buffer[3] == 0x00) {

                        strRes = "写入卡片成功写入数据为";
//                        byte[] cont = getContent(buffer, size);
////                        strRes = getHexStr(cont, 0, cont.length).replace(" ", "");
                    } else {
                        result = new ReturnValue(false, "1", "写卡" + explain + "出错");
                        listener.readDataCallback(result);
                        return;
                    }


                }
                if(cardtype.equals("writeCardProductBlock")){

                    if (size == 6 && buffer[0] == 0x20 && buffer[size - 1] == 0x03 && buffer[2] == 0x00 && buffer[3] == 0x00) {

                        strRes = "写入卡片成功产品写入数据为";
//                        byte[] cont = getContent(buffer, size);
////                        strRes = getHexStr(cont, 0, cont.length).replace(" ", "");
                    } else {
                        result = new ReturnValue(false, "1", "写卡" + explain + "出错");
                        listener.readDataCallback(result);
                        return;
                    }

                }
                //20 00 00  返回数据长度15  卡序列号个数 04 卡序列号 （ 8B 7D EE 52）  00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F  A4 03
                if (cardtype.equals("readCardIdAndProduct")) {
                    if (isOk(buffer, size)) {

                        int dataLength = buffer[3];
                        if (dataLength > 0 && size > 7) {
                            int cardIDLength = buffer[4];//卡片序列号的长度
                            byte[] cardId = new byte[cardIDLength];
                            cardId = reverse(subBytes(buffer, 5, cardIDLength));//逆序输出
//                            PWMPlay();
                            String strResID = bytes2HexString(cardId);

                            byte[] strBlackByte = subBytes(buffer, 9, 16);

                            byte[] strBlackProductByte = subBytes(buffer, 25, 16);
//                            strRes =strResID+"&"+"nide" ;
                            try{
                                strRes = strResID + "&" + decodeChangeChinese(new String(strBlackByte))
                                        +  "&" + decodeChangeChinese(new String(strBlackProductByte)) ;
                            }catch (Exception  e){
                                result = new ReturnValue(false, "1",  "此卡片未正常写入");
                                listener.readDataCallback(result);
                                return;
                            }
                        }
                    } else {
                        result = new ReturnValue(false, "1", explain + "出错");
                        listener.readDataCallback(result);
                        return;
                    }

                }

                //20 00 00  返回数据长度15  卡序列号个数 04 卡序列号 （ 8B 7D EE 52）  00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F  A4 03
                if (cardtype.equals("readCardId")) {
                    if (isOk(buffer, size)) {

                        int dataLength = buffer[3];
                        if (dataLength > 0 && size > 7) {
                            int cardIDLength = buffer[4];//卡片序列号的长度
                            byte[] cardId = new byte[cardIDLength];
                            cardId = reverse(subBytes(buffer, 5, cardIDLength));//逆序输出
//                            PWMPlay();
                            String strResID = bytes2HexString(cardId);

                            byte[] strBlackByte = subBytes(buffer, 9, dataLength - 5);
//                            strRes =strResID+"&"+"nide" ;

                            try{
                                strRes = strResID + "&" + decodeChangeChinese(new String(strBlackByte));
                            }catch (Exception  e){
                                result = new ReturnValue(false, "1",  "此卡片未正常写入");
                                listener.readDataCallback(result);
                                return;
                            }
//                            byte[] strBlackByte  = subBytes(buffer, 9, 16);
//                            String strBlack= bytes2HexString(strBlackByte);
//                            strRes =strResID+"&"+ strBlack;
                        }

//                        byte[] cont = getContent(buffer, size);
//                        strRes = getHexStr(cont, 0, cont.length).replace(" ", "");
                    } else {
                        result = new ReturnValue(false, "1", "写卡" + explain + "出错");
                        listener.readDataCallback(result);
                        return;
                    }

                }


                if (cardtype.equals("readCardNum")) {

                    if (isOk(buffer, size)) {

                        int dataLength = buffer[3];
                        if (dataLength > 0 && buffer.length > 7) {
                            int cardIDLength = buffer[7];//卡片序列号的长度
                            byte[] cardId = new byte[cardIDLength];
                            cardId = reverse(subBytes(buffer, 8, cardIDLength));//逆序输出
//                            PWMPlay();
//                            strRes = "读取卡号:" + bytes2HexString(cardId);
                            strRes = bytes2HexString(cardId);
                        }
                    } else {
                        result = new ReturnValue(false, "-1", "校验" + explain + "应答数据有误:" + hex);
                        listener.readDataCallback(result);
                        return;
                    }

                }

                result = new ReturnValue(true, "0", strRes);


                listener.readDataCallback(result);

                return;
            }
        });
    }

    private boolean isCanLaunchRequest(ReturnValueCallback callback) {
        if (this.getIsLock()) {
            if (callback != null) {
                callback.run(new ReturnValue(false, "99", "请等待上次通讯请求完成"));
            }
            return false;
        }
        this.setLock();
        this.returnValueCallback = callback;
        String msg = this.initSerialPortUtil();
        if (msg == null)
            return true;
        this.callReturnValueCallback(new ReturnValue(false, "-3", msg));
        return true;
    }

    private boolean getIsLock() {
        return _isLocked;
    }

    private void setLock() {
        _isLocked = true;
    }

    private String getHexStr(byte[] buffer, int size) {
        return this.getHexStr(buffer, 0, size, " ");
    }

    private String getHexStr(byte[] buffer, int offset, int len, String split) {
        StringBuilder str = new StringBuilder();
        int end = offset + len;
        for (int i = offset; i < end; i++) {
            String hex = Integer.toHexString(buffer[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            str.append(hex).append(split);
        }
        return str.toString().toUpperCase();
    }

    private String getHexStr(byte[] buffer, int offset, int len) {
        return this.getHexStr(buffer, offset, len, "");
    }

    private byte[] getContent(byte[] data, int size) {
        byte[] cont = new byte[size - 6];
        if (cont.length > 0) {
            System.arraycopy(data, 4, cont, 0, cont.length);
        }
        return cont;
    }

    private byte getXORBack(byte[] data, int index, int end) {
        byte res = this.getXOR(data, index, end);
        return (byte) (~((int) res));
    }

    private byte getXOR(byte[] data, int index, int end) {
        byte t = 0;
        for (int i = index; i < end; i++)
            t ^= data[i];
        return t;
    }

    /**
     * 字节数组逆序
     *
     * @param myByte
     * @return
     */
    public static byte[] reverse(byte[] myByte) {
        byte[] newByte = new byte[myByte.length];

        for (int i = 0; i < myByte.length; i++) {
            newByte[i] = myByte[myByte.length - 1 - i];
        }
        return newByte;
    }

    /**
     * 从一个byte[]数组中截取一部分
     *
     * @param src
     * @param begin
     * @param count
     * @return
     */
    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        for (int i = begin; i < begin + count; i++) bs[i - begin] = src[i];
        return bs;
    }

    /**
     * 字节数组转十六进制字符串
     *
     * @param b
     * @return
     */
    public static String bytes2HexString(byte[] b) {
        StringBuffer ret = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                ret.append("0");
            }
            ret.append(hex.toLowerCase());
        }
        return ret.toString();
    }

    /**
     * 读取卡号
     *
     * @return
     */
    public static byte[] getReadCardId() {
        int len = 7;
        byte[] buf = new byte[len];
        buf[0] = 0x20;
        buf[1] = 0x00;
        buf[2] = 0x21;
        buf[3] = 0x01;
        buf[4] = 0x00;//ReqCode＝0（IDLE），请求天线范围内IDLE状态的卡（HALT状态的除外）
        buf[5] = getBBC(buf[1], buf[2], buf[3], buf[4]);
        buf[6] = 0x03;
        return buf;
    }

    /**
     * 自动读取卡号
     *
     * @return
     */
    public static byte[] getAutoReadCardId() {
        int len = 7;
        byte[] buf = new byte[len];
        buf[0] = 0x20;
        buf[1] = 0x00;
        buf[2] = 0x25;
        buf[3] = 0x01;
        buf[4] = 0x00;//ReqCode＝0（IDLE），请求天线范围内IDLE状态的卡（HALT状态的除外）
        buf[5] = getBBC(buf[1], buf[2], buf[3], buf[4]);
        buf[6] = 0x03;
        return buf;
    }

    /**
     * 校验和。从包号（SEQNR）开始到数据（DATA）的最后一字节异或取反。
     *
     * @param SEQNR
     * @param CMD
     * @param Length
     * @param data
     * @return
     */
    public static byte getBBC(byte SEQNR, byte CMD, byte Length, byte data) {
        return (byte) ~(SEQNR ^ CMD ^ Length ^ data);
    }


    /**
     * 写块005
     *
     * @param data
     * @return
     */
    public static byte[] getWriteBlock(byte[] data) {//data字节数组长度为16

        ByteBuffer buf = ByteBuffer.allocate(23);
        buf.put((byte) 0x20);
        buf.put((byte) 0x00);
        buf.put((byte) 0x23);
        buf.put((byte) 0x11);
        buf.put((byte) 0x01);
        buf.put(data);
        byte temp = (byte) 0x01;
        for (int i = 0; i < data.length; i++) {
            temp = (byte) (temp ^ data[i]);
        }
        byte bcc = (byte) ~((byte) 0x00 ^ (byte) 0x23 ^ (byte) 0x011 ^ temp);//校验和。从包号（SEQNR）开始到数据（DATA）的最后一字节异或取反。
        buf.put(bcc);
        buf.put((byte) 0x03);

        buf.flip();
        byte[] out = new byte[23];
        buf.get(out);
        return out;
    }

    /**
     * 写块006产品
     *
     * @param data
     * @return
     */
    public static byte[] getWriteProductBlock(byte[] data) {//data字节数组长度为16

        ByteBuffer buf = ByteBuffer.allocate(23);
        buf.put((byte) 0x20);
        buf.put((byte) 0x00);
        buf.put((byte) 0x23);
        buf.put((byte) 0x11);
        buf.put((byte) 0x02);
        buf.put(data);
        byte temp = (byte) 0x02;
        for (int i = 0; i < data.length; i++) {
            temp = (byte) (temp ^ data[i]);
        }
        byte bcc = (byte) ~((byte) 0x00 ^ (byte) 0x23 ^ (byte) 0x011 ^ temp);//校验和。从包号（SEQNR）开始到数据（DATA）的最后一字节异或取反。
        buf.put(bcc);
        buf.put((byte) 0x03);

        buf.flip();
        byte[] out = new byte[23];
        buf.get(out);
        return out;
    }
    private byte[] getSetAutoReadBlockProductData() {
        int offset = 0;
        byte[] data = new byte[255];
        data[offset++] = 0x00;
        data[offset++] = 0x26;
        data[offset++] = 0x04;
        data[offset++] = 0x00;
        data[offset++] = 0x00;
//        data[offset++] = 0x19;
        data[offset++] = 0x01;
        data[offset++] = 0x02;
        return this.getSendData(data, offset);
    }

    private byte[] getSetAutoReadBlockData() {
        int offset = 0;
        byte[] data = new byte[255];
        data[offset++] = 0x00;
        data[offset++] = 0x26;
        data[offset++] = 0x04;
        data[offset++] = 0x00;
        data[offset++] = 0x00;
//        data[offset++] = 0x19;
        data[offset++] = 0x01;
        data[offset++] = 0x01;
        return this.getSendData(data, offset);
    }

    private byte[] getSendData(byte[] data, int offset) {
        int index = 0;
        byte[] sendData = new byte[offset + 3];
        sendData[index++] = 0x20;
        System.arraycopy(data, 0, sendData, index, offset);
        index += offset;
        sendData[index++] = this.getXORBack(sendData, 1, index);
        sendData[index] = 0x03;
        return sendData;
    }

    private boolean isOk(byte[] oData, int size) {
        if (size < 6)
            return false;
        byte[] data;
        if (oData[0] == 0x06) {
            data = new byte[size - 1];
            System.arraycopy(oData, 1, data, 0, data.length);
        } else {
            data = oData;
        }
        return data[0] == 0x20 && data[size - 1] == 0x03 && data[size - 2] == this.getXORBack(data, 1, size - 2);
    }

    @Override
    protected void finalize() throws Throwable {
        _isLocked = false;
        closeSerialPort();
        super.finalize();
    }

    private void closeSerialPort() {
        if (mSerialPortUtil != null) {
            mSerialPortUtil.closeSerialPort();
            mSerialPortUtil = null;
        }
    }

    interface ReadDataListener {
        void readDataCallback(ReturnValue result);
    }

    /*
     * 中文转unicode编码
     */
    public static String toUnicode(String s) {
        String as[] = new String[s.length()];
        String s1 = "";
        for (int i = 0; i < s.length(); i++) {
            as[i] = Integer.toHexString(s.charAt(i) & 0xffff);
            s1 = s1 + as[i];
        }
        return s1;
    }

    /*
     * unicode编码转中文
     */
    public static String decodeUnicode(String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }

    private String decodeChangeChinese(String name) {
        String chine = "";
        StringBuffer stringBuilder1 = new StringBuffer(name);
        stringBuilder1.insert(12, "\\u");
        stringBuilder1.insert(8, "\\u");
        stringBuilder1.insert(4, "\\u");
        stringBuilder1.insert(0, "\\u");
        chine = decodeUnicode(stringBuilder1.toString());

        try {
            String ndie =String.valueOf(chine.charAt(3));
            if (String.valueOf(chine.charAt(3)).equals("姚")) {
                chine =  chine.substring(0, 3);
            }
            if (String.valueOf(chine.charAt(2)).equals("姚")) {
                chine = chine.substring(0, 2);
            }
            if (String.valueOf(chine.charAt(1)).equals("姚")) {
                chine = chine.substring(0, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return chine;
    }

    /**

       * 限制只能输入中文

       */

    public static boolean isChineseWord(String str){
        boolean isChinese=false;

        String pattern = "[\u4e00-\u9fa5]+";

        isChinese = Pattern.matches(pattern, str);

        return isChinese;

    }

}
